package com.atguigu.flow.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.flow.entity.Customers;
import com.atguigu.flow.entity.vo.Permissions;
import com.atguigu.flow.mapper.CustomersMapper;
import com.atguigu.flow.mapper.SqlMapper;
import com.atguigu.flow.mapper.SysRoleMapper;
import com.atguigu.flow.service.CustomersService;
import com.atguigu.flow.utils.Workflow;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-08-06
 */
@Service
public class CustomersServiceImpl extends ServiceImpl<CustomersMapper, Customers> implements CustomersService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SqlMapper sqlMapper;

    @Override
    public
    JSONObject customersshowlist(String modulename, String recordid, String username) throws Exception {
        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONArray jsonArray1 = new JSONArray();
        JSONArray jsonArray2 = new JSONArray();
        String userid= sqlMapper.get_userid(username);
        //读取数据库权限列表
        List<Permissions> permissionsList = sysRoleMapper.get_role_Permissions(username);
        json.put("fields", jsonArray1);
        json.put("roles", jsonArray2);
        //System.out.println(json);
        int i = 0;
        try {
            for (i = 0; i < permissionsList.size(); i++) {
                //读取数据库权限字段（Permissions）为字节字段，读到字节流并转为string
                Permissions permissions = permissionsList.get(i);
                System.out.println(permissions.getOrganizationID());
                byte[] datas = permissions.getPermissions();

                String filepath = "";

                if (datas != null) {

                    ByteArrayOutputStream baos = null;


                    // create new ByteArrayOutputStream
                    baos = new ByteArrayOutputStream();

                    // write byte array to the output stream
                    baos.write(datas);

                    // converts buffers using default character set
                    String str = baos.toString();

                    if (baos != null)
                        baos.close();

                    //Permissions为xml文件，解析xml文件，查找对应模块的数据范围及对应模块的隐藏字段列表
                    Workflow.readperxml(str, modulename, permissions.getOrganizationID(), json);
                }

            }      // print
            System.out.println(json);
            jsonArray = json.getJSONArray("roles");
            System.out.println(jsonArray);
            String wheresql="";
            for (i = 0; i < jsonArray.size(); i++) {
                String Range=jsonArray.getJSONObject(i).getString("Range");
                String OrganizationID=jsonArray.getJSONObject(i).getString("OrganizationID");
                if (Range.equals("vrAll"))
                {wheresql=" 1=1 ";
                break;}
                else if (Range.equals("vrOrganization")){
                    if (Strings.isEmpty(wheresql))
                        wheresql="[customers].[UserID] In(Select [RecordID] From Function_Sys_Organization_GetUsers('"
                                +OrganizationID+"'))";
                    else
                        wheresql=wheresql+" or [customers].[UserID] In(Select [RecordID] From Function_Sys_Organization_GetUsers('"
                                +OrganizationID+"'))";
                }
                else if (Range.equals("vrOwn")){
                    if (Strings.isEmpty(wheresql))
                        wheresql="[customers].[UserID]='"+userid+"'";
                    else
                        wheresql=wheresql+"or [customers].[UserID]='"+userid+"'";
                }




            }
            System.out.println(wheresql);
            String sql="select Customers.CustomerNo,Customers.CustomerShortName,Customers.CustomerCorpName,Customers.Country,Customers.lxr,Customers.dh,Customers.yx,Customers.spzt,Customers.tybz from Customers where 1=1";
            if (!Strings.isEmpty(recordid))
            sql=sql+" and recordid=#{recordid}";
            if (!Strings.isEmpty(wheresql))
                sql=sql+" and ("+wheresql+")";

            Map<String, Object> params = new HashMap<>();
            params.put("sql", sql);
            if (Strings.isEmpty(recordid))
            params.put("recordid", recordid);
            List<Customers> customersList = baseMapper.getcusomerlist_map(params);
           // List<Customers> customersList=baseMapper.getcusomerlist(recordid,wheresql);

            //System.out.println(customersList);
            json.put("count", customersList.size());
            json.put("customersList", customersList);

                return json;

        } catch (Exception e) {
            // if I/O error occurs
            e.printStackTrace();
            json.put("error", "error");
            return json;
        }
    }

}
